/*
 * @Author: Xujianchen
 * @Date: 2025-10-17 14:32:46
 * @LastEditTime: 2025-10-20 09:41:15
 * @LastEditors: Xujianchen
 * @Description: 缓存
 */
import { TOKEN, USER_INFO } from '@/const/storage'
import { isObject, isArray } from '@/utils/type'

type StorageType = 'localStorage' | 'sessionStorage'

/**
 * @description: 设置缓存
 * @param {StorageType} key 缓存键
 * @param {*} value 缓存值
 * @param {string} type 缓存类型，localStorage或sessionStorage
 */
export function setStorage(key: string, value: any, type: StorageType = 'localStorage') {
  if (!key) return
  if (isObject(value) || isArray(value)) {
    value = JSON.stringify(value)
  }

  window[type].setItem(key, value)
}

/**
 * @description: 获取缓存
 * @param {string} key 缓存键
 * @param {StorageType} type 缓存类型，localStorage或sessionStorage
 * @param {*} initValue 初始化值，如果缓存不存在则返回此值
 * @return {*} 缓存值
 */
export function getStorage(key: string, type: StorageType = 'localStorage', initValue = null) {
  if (!key) return
  let data: any = window[type].getItem(key)
  try {
    return JSON.parse(data)
  } catch (error) {
    return data || initValue
  }
}

/**
 * @description: 移除单个缓存值
 * @param {string} key 缓存键
 * @param {StorageType} type 缓存类型，localStorage或sessionStorage
 */
export function removeItem(key: string, type: StorageType = 'localStorage') {
  if (!key) return
  window[type].removeItem(key)
}

// token
export const setToken = (value: string) => setStorage(TOKEN, value)
export const getToken = (): string | null => getStorage(TOKEN)
export const removeToken = () => removeItem(TOKEN)

// userInfo
export const setUser = (value: any) => setStorage(USER_INFO, value)
export const getUser = (): any | null => getStorage(USER_INFO)
export const removeUser = () => removeItem(USER_INFO)
